package com.niodata.dp.expression.function.array;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class StringArrayToIntFunction extends AbstractFunction {

  @Override
  public String getName() {
    return "array.int";
  }

  /**
   * convert each int to string.
   *
   * @param env env
   * @param array array
   * @return string array
   */
  public AviatorObject call(Map<String, Object> env, AviatorObject array) {
    Object v = array.getValue(env);
    Object[] varray = null;
    if (List.class.isAssignableFrom(v.getClass())) {
      List list = (List) v;
      varray = list.toArray(new Object[list.size()]);
    } else {
      varray = (Object[]) array.getValue(env);
    }
    int[] sarray = new int[varray.length];
    for (int i = 0; i < varray.length; i++) {
      sarray[i] = varray[i] != null ? Integer.parseInt(varray[i].toString()) : 0;
    }
    Object result = sarray;
    if (List.class.isAssignableFrom(v.getClass())) {
      result = Arrays.asList(result);
    }
    return FunctionUtils.wrapReturn(result);
  }
}
